package toy.keli.picmap;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.io.File;
import java.text.SimpleDateFormat;

import toy.keli.picmap.model.Model;
import toy.keli.picmap.model.db;
import toy.keli.picmap.model.def;
import toy.keli.picmap.model.path;
import toy.keli.picmap.model.pic;
import toy.keli.picmap.model.system;
import toy.keli.picmap.service.Connection;
import toy.keli.picmap.service.FindPicService;
import toy.keli.picmap.tools.Control;


/**
 * 配置路径等参数
 */
public class ConfigActivity extends BaseActivity {
    public static final String TAG = "config";
    private Connection mConnection;
    private ListView listView;
    private BaseAdapter listAdapter;
    long lastTime=0;
    def pathAll=new def();
    def addItem;
    private int requestCode;
    private int resultCode;
    @Nullable
    private Intent data;

    @RequiresApi(api = Build.VERSION_CODES.M)
    protected void onCreate(Bundle savedInstanceState) {
        //CustomTitle.Show(this, true,null,true,false);
        super.onCreate(savedInstanceState);
        initData();
        initView();
        initEvent();
        //android显示后台进程进度  https://jingyan.baidu.com/article/6c67b1d6e5a8e52786bb1e7f.html
        if(pathAll.size()==1) {
            if(!getPermission(Manifest.permission.READ_EXTERNAL_STORAGE,()->{ recreate(); })){
                msg("请先授权媒体读取权限");
                return;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    checkNewData();
                }
            }).start();
        }
    }

    private void initData() {
        Model.iterator paths = new path().findAll("count>0");
        addItem=new def.dict("path","长按重新读取媒体数据","count","重置","index","刷新");
        def map=new def();
        addItem.set("map",map);
        for(Model m : paths){
            path p=(path)m;
            lastTime=Math.max(lastTime,p.uptime);
            pathAll.push(p);
            map.push(p.path);
        }
        lastTime=lastTime/1000;
        pathAll.push(addItem);
    }

    private void initEvent() {
        listView.setOnItemClickListener((k,v,index,args) -> {
            if(index==pathAll.size()-1) {
                new Thread(new Runnable() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void run() {
                        checkNewData();
                    }
                }).start();
            }else{
                Intent intent= new Intent(this,BmapActivity.class);
                intent.putExtra("pid", String.valueOf(v.getTag()));
                startActivity(intent);
            }
        });

        listView.setOnItemLongClickListener((k,v,index,args)->{
            if(index==pathAll.size()-1) {
                new db(ConfigActivity.this).clearAll();
                refresh();
            }else{
                path pathItem=(path)pathAll.get(index).source();
                int pid=pathItem.id;
                String path=pathItem.path;
                popupMenu(v,R.menu.config_popupmenu,(item)->{
                    MenuItem m=(MenuItem)item;
                    switch (String.valueOf(m.getTitle())){
                        case "复制路径":
                            system.copy(this,pathAll.get(index).get("path").toString());
                            system.msg(this,"内容复制成功");
                            break;
                        case "删除":
                            ConfirmDialog("警告","确认要删除这个路径嘛？",()->{
                                new pic().find().where("pid="+pid).delete();
                                new path(pid).remove();
                                pathAll.remove(index);
                                refresh();
                            });
                            break;
                        case "重置":
                            msg("待开发");
                            new pic().find().where("pid="+pid).delete();
                            pic.findByPath(path,(i,name,n)->{
                                pathItem.count=i;
                                pathItem.path=name;
                                pathItem.intime=n;
                                Message msg=new Message();
                                ConfigActivity.this.myMessageHeader.sendMessage(msg);
                            });
                            break;
                        case "打开路径":
                            //android 使用代码打开文件浏览器并显示指定目录 https://blog.csdn.net/weixin_30904593/article/details/95552744
                            openApp("com.estrongs.android.pop","com.estrongs.android.pop.view.FileExplorerActivity",(i)->{
                                Intent intent=(Intent)i;
                                intent.setData(Uri.fromFile(new File(path)));
                            });
                            break;
                    }
                });
            }
            return true;
        });

        
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        listView=findViewById(R.id.listView);
        listView.setAdapter(listAdapter=new BaseAdapter() {
            @Override
            public int getCount() {
                return pathAll.size();
            }

            @Override
            public Object getItem(int position) {
                return pathAll.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (null == convertView) {
                    convertView = View.inflate(ConfigActivity.this, R.layout.demo_info_item, null);
                }
                TextView title = convertView.findViewById(R.id.title);
                TextView time = convertView.findViewById(R.id.time);
                TextView desc = convertView.findViewById(R.id.desc);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Object pv=pathAll.get(position).source();

                if(addItem.equals(pv)){
                    title.setText(""+addItem.get("index")+"/"+addItem.get("count"));
                    time.setText("");
                    desc.setText(addItem.get("path").toString());
                    return convertView;
                }
                path p=(path)pv;
                String uptime= formatter.format(p.uptime);
                String index="";
                title.setText(index+p.count+"张");
                time.setText(uptime);
                desc.setText(p.path);
                convertView.setTag(p.id);
                return convertView;
            }
        });
    }

    private void startbackService() {
        mConnection= new Connection();
        Intent intent =new Intent(ConfigActivity.this,FindPicService.class);
        startService(intent);
    }

    private void serviceDo(String method,Object... args){
        mConnection.run(this,method,args);
    }

    @SuppressLint("NewApi")
    public void refresh() {
        //在Android中如何重新加载activity  https://cloud.tencent.com/developer/ask/40829?from=14588
        if(pathAll.size()==1) {
            finish();
            startActivity(new Intent(this, BmapActivity.class));
        }else
            recreate();
    }
    private void checkNewData() {
        // 获取SD卡的文件，有的比较耗时，一般我们不在Main-Thread线程中去做
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver resolver = getContentResolver();
        //Android中Cursor的方法 https://blog.csdn.net/ching_zhi/article/details/53835334
        Cursor cursor = resolver.query(uri,new String[]{
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.LATITUDE,
                MediaStore.Images.Media.LONGITUDE,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media._ID
        },"date_added > "+lastTime,null,"date_added desc",null);


        //cursor.moveToFirst();
        int sum=cursor.getCount(),i=0,max= Control.limit,addCount=0;
        def pathAdd=new def();
        if(Math.min(sum,max)>0)
        addItem.set("count",Math.min(sum,max));
        while (cursor.moveToNext() && i++ <max) {
            String pathName = cursor.getString(0);
            long time = cursor.getLong(1);
            float latitude = cursor.getFloat(cursor.getColumnIndex(MediaStore.Images.Media.LATITUDE));
            float longitude = cursor.getFloat(cursor.getColumnIndex(MediaStore.Images.Media.LONGITUDE));

            pic p = (latitude == 0 && longitude == 0) ? new pic(pathName,time): new pic(pathName,time,longitude,latitude);
            p.wgs2bd();
            String name=pathName.substring(0,pathName.lastIndexOf("/"));
            path pp=path.get(name);
            p.pid=pp.id;
            boolean b=p.save();
            if(b)  {
                def pathNow=pathAdd.get(name);
                if(pathNow.isEmpyt())  pathAdd.set(name,pathNow=new def());
                pathNow.push(p.id);
                if(pathNow.size()>100) {
                    pp.add(pathNow.size());
                    pathNow.empyt();
                }

                addItem.set("index",i);
                addItem.set("path",pathName);
                Message m=new Message();
                ConfigActivity.this.myMessageHeader.sendMessage(m);
                addCount++;
            }
        }
        cursor.close();
        if(pathAdd.size()>0) {
            for (def name : pathAdd)
                path.get(name.toString()).add(pathAdd.get(name).size());

            Message m = new Message();
            Bundle d = new Bundle();
            d.putString("sum", String.valueOf(addCount));
            m.setData(d);
            ConfigActivity.this.myMessageHeader.sendMessage(m);
        }
    }


    Handler myMessageHeader=new Handler(){
        public void handleMessage(Message msg){
            String sum=msg.getData().getString("sum");
            if(sum==null) {
                listAdapter.notifyDataSetChanged();
            }else if(sum.equals("0")){
                system.msg(ConfigActivity.this, "没有新图片了");
            }else{
                msg( "新增图片"+sum+"张");
                refresh();
            }

            super.handleMessage(msg);
        }
    };
}